package com.atguigu.gmall.seckill.config;

import com.atguigu.gmall.common.cache.GmallCacheAspect;
import com.atguigu.gmall.common.config.ItemServiceRedissonConfig;
import com.atguigu.gmall.common.config.MybatisPlusConfig;
import com.atguigu.gmall.feign.AppFeignConfig;
import com.atguigu.gmall.mq.AppRabbitConfig;
import com.atguigu.gmall.seckill.component.SecKillLocalCache;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@EnableScheduling
@EnableAspectJAutoProxy
@EnableFeignClients({"com.atguigu.gmall.feign.order"})
@Configuration
@Import({MybatisPlusConfig.class, AppFeignConfig.class, ItemServiceRedissonConfig.class,
        GmallCacheAspect.class, AppRabbitConfig.class})
public class SeckillConfig {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, SecKillLocalCache seckillLocalCache) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅主题，seckillLocalCache这个消息监听器监听redis中 channel_key通道的内容
        container.addMessageListener(seckillLocalCache, new PatternTopic(SecKillLocalCache.channel_key));
        return container;
    }

    @Bean
    ThreadPoolExecutor asyncExecutor(){
        /**
         * int corePoolSize,
         *                               int maximumPoolSize,
         *                               long keepAliveTime,
         *                               TimeUnit unit,
         *                               BlockingQueue<Runnable> workQueue,
         *                               ThreadFactory threadFactory,
         *                               RejectedExecutionHandler handler
         * DiscardOldestPolicy: 拒绝策略；抛弃老的。
         */
        return new ThreadPoolExecutor(2,
                2,
                1,
                TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
    }
}
